package com.redoor.app.stake.workflow.service.impl;

import com.redoor.app.stake.basicdata.model.BaseStake;
import com.redoor.app.stake.basicdata.model.RegistrationApplyForRedis;
import com.redoor.app.stake.workflow.commons.WorkFlowStatus;
import com.redoor.app.stake.workflow.dao.BaseWorkorderMapper;
import com.redoor.app.stake.workflow.model.BaseWorkorder;
import com.redoor.app.stake.workflow.model.controllerModel.WorkOrderCriteria;
import com.redoor.app.stake.workflow.model.serviceModel.BaseWorkOrderServiceBean;
import com.redoor.app.stake.workflow.model.serviceModel.WorkOrderNumBean;
import com.redoor.app.stake.workflow.service.*;
import com.redoornetwork.framework.core.exception.ServiceException;
import com.yotouch.app.stake.StakeConsts;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class WorkOrderServiceImpl implements WorkOrderService {
    private static final Logger logger = LoggerFactory.getLogger(WorkOrderService.class) ;

    @Autowired
    BaseWorkorderService baseWorkorderService;

    @Autowired
    RegistrationApplyWorkOrderService registrationApplyWorkOrderService;

    @Autowired
    MaintenanceApplyWorkOrderService maintenanceApplyWorkOrderService;

    @Autowired
    MaintenaceChargeWorkOrderService maintenaceChargeWorkOrderService;

    @Override
    public int reApplySaveAll(List<RegistrationApplyForRedis> registrationApplyForRedisList) {
        return registrationApplyWorkOrderService.createAll(registrationApplyForRedisList);
    }

    @Override
    public int reApplyAccept(WorkOrderCriteria workOrderCriteria) {
        return registrationApplyWorkOrderService.accept(workOrderCriteria);
    }

    @Override
    public int reApplyReject(WorkOrderCriteria workOrderCriteria) {
        return registrationApplyWorkOrderService.reject(workOrderCriteria);
    }

    @Override
    public int maApplySave(BaseStake stake,String mqUuid) {

        if (null == stake || StringUtils.isBlank(stake.getUuid())){
            throw new ServiceException(WorkFlowStatus.PARAM_IS_EMPTY);
        }
        /*处于试运行的桩才生成工单*/
        if (StakeConsts.STATION_STATUS_TRIAL == stake.getStakestatus()){
            /*判断目标桩的维护工单是否都已经关闭*/
            boolean canCreateMaApplyWorkOrder = true;
            List<BaseWorkorder> maApplyWorkOrderList = baseWorkorderService.findMainApplyByTargetUuid(stake.getUuid());
            Iterator<BaseWorkorder> maApplyWorkOrderListIterator = maApplyWorkOrderList.iterator();
            while (maApplyWorkOrderListIterator.hasNext()){
               BaseWorkorder maApplyWorkOrder = maApplyWorkOrderListIterator.next();
               if (Integer.parseInt(WorkFlowStatus.WORKORDER_STATUS_FINISH.getCode()) != maApplyWorkOrder.getWorkstatus()){
                   canCreateMaApplyWorkOrder = false;
               }
            }
            /*目标桩的维护工单都关闭,生成新的桩维护工单*/
            if (canCreateMaApplyWorkOrder){
                return maintenanceApplyWorkOrderService.create(stake,mqUuid);
            }else{
                logger.info("stake:{} already has mainApplyWorkOrder", stake.getUuid());
            }
        }else{
            logger.info("stake:{} stakeStatus != 2,failed to form mainApplyWorkOrder", stake.getUuid());
            // FIXME: 2018/4/1 0001 未处于试运行的桩尝试生成桩维护工单该怎么处理
        }
        return 0;
    }

    @Override
    public int maApplySubmit(String uuid) {
        BaseWorkorder maApWorkorder = baseWorkorderService.findById(uuid);
        /*判断维护工单是否提交成功*/
        if (0 < maintenanceApplyWorkOrderService.submit(maApWorkorder)){
            /*查找维护工单对应的审核工单*/
            List<BaseWorkorder> maChWorkOrderList = baseWorkorderService.findMainChargeByTargetUuid(maApWorkorder.getTargetuuid());
            /*对应的审核工单数量为零,新建一个*/
            if (0 == maChWorkOrderList.size()){
                return maintenaceChargeWorkOrderService.create(maApWorkorder);
            /*对应的审核工单存在一个 且 处于拒绝状态*/
            }else if ( 1 == maChWorkOrderList.size()
                    && Integer.parseInt(WorkFlowStatus.WORKORDER_STATUS_REJECT.getCode()) == maChWorkOrderList.get(0).getWorkstatus()){
                /*激活这个工单*/
                return maintenaceChargeWorkOrderService.active(maChWorkOrderList.get(0));
            }else if (1 < maChWorkOrderList.size()){
                /*数据错误,桩维护工单对应多个审核工单*/
                logger.error("data_error,maintenaceChargeWorkOrder_corresponding_not_only_one_maintenaceApplyWorkOrders,mainCharge_uuid:"+maApWorkorder.getUuid());
            }
        }
        return 0;
    }

    @Override
    public int maChargeAccept(WorkOrderCriteria workOrderCriteria) {
        BaseWorkorder maChWokOrder = baseWorkorderService.findById(workOrderCriteria.getUuid());
        /*审核通过*/
        if (0 < maintenaceChargeWorkOrderService.accept(workOrderCriteria)){
            /*审核通过后,关闭对应的维护工单*/
            return maintenanceApplyWorkOrderService.close(maChWokOrder.getTargetuuid());
        }
        return 0;
    }

    @Override
    public int maChargeReject(WorkOrderCriteria workOrderCriteria) {
        BaseWorkorder maChWorkOrder = baseWorkorderService.findById(workOrderCriteria.getUuid());
        /*拒绝这个工单*/
        if (0 < maintenaceChargeWorkOrderService.reject(workOrderCriteria)){

            /*激活桩维护工单*/
            return maintenanceApplyWorkOrderService.active(maChWorkOrder.getTargetuuid());

        }
        return 0;
    }


    @Override
    public List<BaseWorkOrderServiceBean> qryTodoWorkOrder(WorkOrderCriteria baseWorkorderCriteria) {
        baseWorkorderCriteria.setTodoOrDone(getTodoStatus());
        /*添加待审核状态,然后查列表*/
        return baseWorkorderService.qryWorkOrder(baseWorkorderCriteria);
    }

    @Override
    public int qryTodoWorkOrderNum(WorkOrderCriteria baseWorkorderCriteria) {
        baseWorkorderCriteria.setTodoOrDone(getTodoStatus());
        return baseWorkorderService.qryWorkOrderNum(baseWorkorderCriteria);
    }

    @Override
    public List<BaseWorkOrderServiceBean> qryDoneWorkOrder(WorkOrderCriteria baseWorkorderCriteria) {
        baseWorkorderCriteria.setTodoOrDone(getDoneStatus());
        return baseWorkorderService.qryWorkOrder(baseWorkorderCriteria);
    }

    @Override
    public int qryDoneWorkOrderNum(WorkOrderCriteria baseWorkorderCriteria) {
        baseWorkorderCriteria.setTodoOrDone(getDoneStatus());
        return baseWorkorderService.qryWorkOrderNum(baseWorkorderCriteria);
    }

    @Override
    public WorkOrderNumBean countWorkOrderNum() {
        return baseWorkorderService.countWorkOrderNum();
    }

    /**
     *  查询中需要使用的 待办列表参数
     *
     * @author ZhangMumu
     * @date 2018/3/30 0030 20:05
     * @param
     * @return
     */
    private List<String> getTodoStatus(){
        List<String> todoStatus = new ArrayList<>(2);
        /*添加 审核中 状态*/
        todoStatus.add(WorkFlowStatus.WORKORDER_STATUS_APPLYING.getCode());
        return todoStatus;
    }

    /**
     *  查询中需要使用的 已办列表参数
     *
     * @author ZhangMumu
     * @date 2018/3/30 0030 20:05
     * @param
     * @return
     */
    private List<String> getDoneStatus(){
        List<String> doneStatus = new ArrayList<>(2);
        /*添加 审核中 状态*/
        doneStatus.add(WorkFlowStatus.WORKORDER_STATUS_FINISH.getCode());
        /*添加 已通过 状态*/
        doneStatus.add(WorkFlowStatus.WORKORDER_STATUS_ACCEPT.getCode());
        /*添加 已通过 状态*/
        doneStatus.add(WorkFlowStatus.WORKORDER_STATUS_REJECT.getCode());
        return doneStatus;
    }
}
